package utils

import (
	"codejy/structdef"
	"fmt"
	"strconv"
	"time"
)

// 是否开启代码执行时间统计
var IsOpenCodeTime = true
var timeConsuming int64 = 100 //100毫秒

// 计算代码执行时间
func CodeExecutionTime(typeName string, threadStore *structdef.ThreadStore, exec func()) {
	if IsOpenCodeTime {
		//计算代码执行时间
		start := time.Now()
		exec()
		end := time.Now()
		milliseconds := end.Sub(start).Milliseconds()
		//判断是否大于指定微妙
		if milliseconds > timeConsuming {
			code := threadStore.Code
			m, p := threadStore.MapCodeTime[typeName]
			if !p {
				m = make(map[structdef.LineCodeDefinition]int)
				threadStore.MapCodeTime[typeName] = m
			}
			i, p1 := m[code]
			if p1 {
				//如果已经存在,那么就判断是否大于当前的执行时间,如果大于,那么就替换
				if i < int(milliseconds) {
					m[code] = int(milliseconds)
				}
			} else {
				m[code] = int(milliseconds)
			}
		}
	} else {
		exec()
	}

}

// 打印有问题的代码
func PrintCodeExecutionTime(threadStore *structdef.ThreadStore) {
	if len(threadStore.MapCodeTime) > 0 {
		fmt.Println("================================执行时间过长的行代码(>" + strconv.FormatInt(timeConsuming, 10) + "毫秒):====================================")
		for k, v := range threadStore.MapCodeTime {
			for k1, v1 := range v {
				fmt.Println("类型: ", k, "可疑行代码: ", k1, "累积执行时间: ", v1, "毫秒")
			}
		}
	}
}

func CodeTime(exec func()) {
	//计算代码执行时间
	start := time.Now()
	exec()
	end := time.Now()
	microseconds := end.Sub(start).Microseconds()
	fmt.Println("代码执行时间: ", microseconds, "微妙")
	//判断是否大于指定微妙,暂停
	if microseconds > timeConsuming {
		time.Sleep(time.Second * 10)
	}
}
